use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn load_conversion_table(file_path: &str) -> HashMap<String, String> {
    let file = File::open(file_path).expect("Cannot open file");
    let reader = BufReader::new(file);
    let mut map = HashMap::new();

    for line in reader.lines() {
        let line = line.expect("Cannot read line");
        let parts: Vec<&str> = line.split(',').collect();
        if parts.len() == 2 {
            map.insert(parts[0].to_string(), parts[1].to_string());
        }
    }

    map
}

pub fn converter(input: &str, tp: &str) -> String {
    let conversion_table = match tp {
        "s2t" => load_conversion_table("src/zh2Hant.csv"),
        "t2s" => load_conversion_table("src/zh2Hans.csv"),
        _ => panic!("Unknown conversion type"),
    };

    let mut result = String::new();
    let mut i = 0;
    let input_chars: Vec<char> = input.chars().collect();
    while i < input_chars.len() {
        let mut matched = false;
        for j in (i + 1..=input_chars.len()).rev() {
            let substr: String = input_chars[i..j].iter().collect();
            if let Some(replacement) = conversion_table.get(&substr) {
                result.push_str(replacement);
                i = j;
                matched = true;
                break;
            }
        }
        if !matched {
            result.push(input_chars[i]);
            i += 1;
        }
    }

    result
}

